package cloud.maque.sso.server.GrantTypeHandler;

import cloud.maque.auth.fegin.AuthUserFeginClient;
import cloud.maque.auth.model.BaseUserModel;
import cloud.maque.common.core.response.R;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.oauth2.SaOAuth2Manager;
import cn.dev33.satoken.oauth2.data.model.AccessTokenModel;
import cn.dev33.satoken.oauth2.data.model.request.RequestAuthModel;
import cn.dev33.satoken.oauth2.granttype.handler.SaOAuth2GrantTypeHandlerInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 第三方的Oauth2授权模式处理器
 */
@Component
public class ThridOauth2GrantTypeHandler implements SaOAuth2GrantTypeHandlerInterface {


    @Autowired
    AuthUserFeginClient authUserFeginClient;

    @Override
    public String getHandlerGrantType() {
        return "third_oauth2";
    }

    @Override
    public AccessTokenModel getAccessToken(SaRequest req, String clientId, List<String> scopes) {

        // 获取前端提交的参数
        String userId = req.getParamNotNull("thirdUserId");
        String thirdType = req.getParamNotNull("thirdType");

        //查找第三方的用户
        R<BaseUserModel> userModelR = authUserFeginClient.GetUserByThrid(thirdType, userId);
        if (userModelR.getCode() == 200) {
            BaseUserModel userModel = userModelR.getData();
            userId = userModel.getUserId();
        } else {
            throw new RuntimeException("错误：" + userModelR.getMsg());
        }

        // 4、构建 ra 对象
        RequestAuthModel ra = new RequestAuthModel();
        ra.clientId = clientId;
        ra.loginId = userId;
        ra.scopes = scopes;

        // 5、生成 Access-Token
        AccessTokenModel at = SaOAuth2Manager.getDataGenerate().generateAccessToken(ra, true);
        return at;
    }
}
